package gui.view;

import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Graphics;
import java.util.Locale;

import javax.swing.JLabel;

import gui.parser.Attr;
import gui.parser.ColorFactory;

public class TextView extends View {
	private JLabel label;
	protected String text;
	protected int textSize;
	protected Color textColor;
	protected String textFont;
	protected String textStyle;
	private int style;
	protected Font font;

	public TextView(Attr attr) {
		super(attr);
	}

	@Override
	public void init() {
		super.init();
		label = new TextViewLabel();
		label.setOpaque(true);
		text = getAttr("gui:text");
		textSize = getIntAttr("gui:textSize", 14);
		textStyle = getAttr("gui:textStyle");
		textFont = getAttr("gui:textFont");
		String m;
		m = getAttr("gui:textColor");
		if (m != null) {
			if ((textColor = ColorFactory.build(m)) != null) {

			} else if (m.startsWith("@Color")) {

			}
		}
	}

	/**
	 * 创建字体对象
	 */
	private void buildFont() {
		if (textStyle != null)
			switch (textStyle.toLowerCase(Locale.CHINA)) {
			case "bold":
				style = Font.BOLD;
				break;
			}
		font = new Font(textFont, style, textSize);
	}

	@Override
	public void invalidate() {
		super.invalidate();
		buildFont();
		setBounds();
		label.setText(text);
		if (font != null)
			label.setFont(font);
	}

	public void setText(String text) {
		this.text = text;
		invalidate();
	}

	public String getText() {
		return text;
	}

	@Override
	public Component getView() {
		return label;
	}

	private class TextViewLabel extends JLabel {
		/**
		 * 
		 */
		private static final long serialVersionUID = 2819162918789674118L;

		@Override
		public void paint(Graphics g) {

			// super.paint(g);
			// 背景
			if (bacground_color != null) {
				g.setColor(bacground_color);
				g.fillRect(0, 0, width, height);
			} else if (bacground_resource != 0) {
				g.drawImage(getResource().getImage(bacground_resource).getImage(), 0, 0, width, height, null);
			}
			// 字体
			g.setColor(textColor == null ? Color.black : textColor);
			g.drawString(text, paddingLeft, paddingTop + g.getFontMetrics(getFont()).getAscent());
		}
	}
}
